using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using ThridGroup.ERP.Application.Contracts.ProductionSystem;
using ThridGroup.ERP.ProductionSystem;
using ThridGroup.ERP.Application.Contracts.DTO;

namespace ThridGroup.ERP.Web.Areas.ProductionSystem.Controllers
{
    [Area("ProductionSystem")]
    [Route("ProductionSystem/[controller]")]
    public class OutgoingInspectionController : AbpController
    {
        private readonly IOutgoingInspectionService _outgoingInspectionService;
        private readonly ILogger<OutgoingInspectionController> _logger;

        public OutgoingInspectionController(
            IOutgoingInspectionService outgoingInspectionService,
            ILogger<OutgoingInspectionController> logger)
        {
            _outgoingInspectionService = outgoingInspectionService;
            _logger = logger;
        }

        [HttpGet]
        [Route("")]
        [Route("Index")]
        public IActionResult Index()
        {
            _logger.LogInformation("访问出货检验管理页面");
            return View();
        }

        [HttpGet]
        [Route("Edit")]
        [Route("Edit/{id}")]
        public async Task<IActionResult> Edit(int? id)
        {
            try
            {
                _logger.LogInformation($"访问出货检验编辑页面，ID：{id}");

                if (id.HasValue)
                {
                    var model = await _outgoingInspectionService.GetOutgoingInspection(id.Value);
                    if (model == null)
                    {
                        _logger.LogWarning($"未找到出货检验记录，ID：{id.Value}");
                        return View(new OutgoingInspectionDto());
                    }
                    return View(model);
                }
                
                return View(new OutgoingInspectionDto());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"加载出货检验编辑页面失败，ID：{id}");
                // 即使发生错误也要返回一个空模型，避免页面崩溃
                return View(new OutgoingInspectionDto());
            }
        }

        [HttpGet]
        [Route("GetOutgoingInspections")]
        public async Task<IActionResult> GetOutgoingInspections(string outgoingCode = null, string outgoingName = null, string customer = null, string batch = null, string productCode = null, string productName = null, string testingResult = null, int page = 1, int limit = 10)
        {
            try
            {
                _logger.LogInformation($"开始获取出货检验列表, 页码: {page}, 每页数量: {limit}");
                
                // 尝试从服务层获取数据
                List<OutgoingInspectionDto> allData;
                try
                {
                    allData = await _outgoingInspectionService.GetOutgoingInspections();
                    _logger.LogInformation($"从服务层获取出货检验列表成功，共获取{allData?.Count ?? 0}条记录");
                }
                catch (Exception serviceEx)
                {
                    _logger.LogError(serviceEx, "从服务层获取出货检验列表失败");
                    return Json(new { code = 1, msg = "获取数据失败：" + serviceEx.Message, count = 0, data = new List<object>() });
                }
                
                // 检查获取的数据
                if (allData == null)
                {
                    _logger.LogWarning("服务层返回的出货检验列表为null");
                    return Json(new { code = 0, msg = "获取成功，但无数据", count = 0, data = new List<object>() });
                }

                try 
                {
                    // 应用筛选条件并添加空值保护
                    if (!string.IsNullOrWhiteSpace(outgoingCode))
                    {
                        allData = allData.Where(x => x?.OutgoingCode != null && x.OutgoingCode.Contains(outgoingCode, StringComparison.OrdinalIgnoreCase)).ToList();
                    }

                    if (!string.IsNullOrWhiteSpace(outgoingName))
                    {
                        allData = allData.Where(x => x?.OutgoingName != null && x.OutgoingName.Contains(outgoingName, StringComparison.OrdinalIgnoreCase)).ToList();
                    }

                    if (!string.IsNullOrWhiteSpace(customer))
                    {
                        allData = allData.Where(x => x?.Customer != null && x.Customer.Contains(customer, StringComparison.OrdinalIgnoreCase)).ToList();
                    }

                    if (!string.IsNullOrWhiteSpace(batch))
                    {
                        allData = allData.Where(x => x?.Batch != null && x.Batch.Contains(batch, StringComparison.OrdinalIgnoreCase)).ToList();
                    }

                    if (!string.IsNullOrWhiteSpace(productCode))
                    {
                        allData = allData.Where(x => x?.ProductCode != null && x.ProductCode.Contains(productCode, StringComparison.OrdinalIgnoreCase)).ToList();
                    }

                    if (!string.IsNullOrWhiteSpace(productName))
                    {
                        allData = allData.Where(x => x?.ProductName != null && x.ProductName.Contains(productName, StringComparison.OrdinalIgnoreCase)).ToList();
                    }

                    if (!string.IsNullOrWhiteSpace(testingResult))
                    {
                        allData = allData.Where(x => x?.TestingResult != null && x.TestingResult.Contains(testingResult, StringComparison.OrdinalIgnoreCase)).ToList();
                    }

                    // 按ID排序
                    var orderedData = allData.OrderBy(x => x.Id).ToList();
                    
                    // 计算总记录数
                    int totalCount = orderedData.Count;
                    
                    // 进行分页
                    var pagedData = orderedData
                        .Skip((page - 1) * limit)
                        .Take(limit)
                        .ToList();

                    _logger.LogInformation($"成功获取出货检验列表，总记录数: {totalCount}, 当前页记录数: {pagedData.Count}");
                    
                    // 返回标准格式的数据，使用count表示总记录数
                    var result = new
                    {
                        code = 0,
                        msg = "获取成功",
                        count = totalCount,
                        data = pagedData.Select(x => new
                        {
                            id = x.Id,
                            outgoingCode = x.OutgoingCode ?? "",
                            outgoingName = x.OutgoingName ?? "",
                            customer = x.Customer ?? "",
                            batch = x.Batch ?? "",
                            productCode = x.ProductCode ?? "",
                            productName = x.ProductName ?? "",
                            specifications = x.Specifications ?? "",
                            unitt = x.Unitt ?? "",
                            send = x.Send,
                            testingNum = x.TestingNum,
                            unqualifiedNum = x.UnqualifiedNum,
                            testingResult = x.TestingResult ?? "",
                            shipmentDate = x.ShipmentDate,
                            testingDate = x.TestingDate,
                            testingPerson = x.TestingPerson ?? "",
                            state = x.State
                        }).ToList()
                    };

                    _logger.LogInformation($"返回JSON结果：{System.Text.Json.JsonSerializer.Serialize(result)}");
                    return Json(result);
                }
                catch (Exception filterEx)
                {
                    _logger.LogError(filterEx, "处理筛选和分页数据时出错");
                    return Json(new { code = 1, msg = "处理数据失败：" + filterEx.Message, count = 0, data = new List<object>() });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取出货检验列表失败");
                _logger.LogError($"异常详情：{ex.Message}, StackTrace: {ex.StackTrace}");
                if (ex.InnerException != null)
                {
                    _logger.LogError($"内部异常：{ex.InnerException.Message}, StackTrace: {ex.InnerException.StackTrace}");
                }
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, count = 0, data = new List<object>() });
            }
        }

        [HttpGet]
        [Route("Get/{id}")]
        public async Task<IActionResult> GetOutgoingInspection(int id)
        {
            try
            {
                _logger.LogInformation($"开始获取出货检验，ID：{id}");
                if (id <= 0)
                {
                    _logger.LogWarning($"无效的出货检验ID：{id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                var model = await _outgoingInspectionService.GetOutgoingInspection(id);
                if (model == null)
                {
                    _logger.LogWarning($"未找到指定的出货检验，ID：{id}");
                    return Json(new { code = 1, msg = "未找到指定的出货检验" });
                }

                _logger.LogInformation($"成功获取出货检验，ID：{id}");
                return Json(new { code = 0, msg = "", data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取出货检验失败，ID：{id}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Add")]
        public async Task<IActionResult> AddOutgoingInspection([FromBody] OutgoingInspectionDto dto)
        {
            try
            {
                var requestJson = System.Text.Json.JsonSerializer.Serialize(dto);
                _logger.LogInformation($"开始添加出货检验，请求数据: {requestJson}");
                
                if (dto == null)
                {
                    _logger.LogWarning("添加出货检验时提交的数据为空");
                    return Json(new { code = 1, msg = "提交的数据不能为空" });
                }

                // 验证必填字段
                if (string.IsNullOrWhiteSpace(dto.OutgoingCode))
                {
                    _logger.LogWarning("添加出货检验时编码为空");
                    return Json(new { code = 1, msg = "出货检验单编号不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.OutgoingName))
                {
                    _logger.LogWarning("添加出货检验时名称为空");
                    return Json(new { code = 1, msg = "验单名称不能为空" });
                }
                
                _logger.LogInformation($"准备调用服务层添加出货检验");
                
                int result = await _outgoingInspectionService.AddOutgoingInspection(dto);
                
                _logger.LogInformation($"服务层添加出货检验成功，返回ID：{result}");
                
                return Json(new { 
                    code = 0, 
                    msg = "添加成功", 
                    data = new { id = result } 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加出货检验失败");
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Update")]
        public async Task<IActionResult> UpdateOutgoingInspection([FromBody] OutgoingInspectionDto dto)
        {
            try
            {
                var requestJson = System.Text.Json.JsonSerializer.Serialize(dto);
                _logger.LogInformation($"开始更新出货检验，请求数据: {requestJson}");
                
                if (dto == null)
                {
                    _logger.LogWarning("更新出货检验时提交的数据为空");
                    return Json(new { code = 1, msg = "提交的数据不能为空" });
                }

                if (dto.Id <= 0)
                {
                    _logger.LogWarning($"更新出货检验时ID无效：{dto.Id}");
                    return Json(new { code = 1, msg = "出货检验ID无效" });
                }

                // 验证必填字段
                if (string.IsNullOrWhiteSpace(dto.OutgoingCode))
                {
                    _logger.LogWarning("更新出货检验时编码为空");
                    return Json(new { code = 1, msg = "出货检验单编号不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.OutgoingName))
                {
                    _logger.LogWarning("更新出货检验时名称为空");
                    return Json(new { code = 1, msg = "验单名称不能为空" });
                }
                
                _logger.LogInformation($"准备调用服务层更新出货检验，ID：{dto.Id}");
                
                int result = await _outgoingInspectionService.UpdateOutgoingInspection(dto);
                
                _logger.LogInformation($"服务层更新出货检验成功，ID：{result}");
                
                return Json(new { 
                    code = 0, 
                    msg = "更新成功", 
                    data = new { id = result } 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新出货检验失败");
                return Json(new { code = 1, msg = "更新失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Delete/{id}")]
        public async Task<IActionResult> DeleteOutgoingInspection(int id)
        {
            try
            {
                _logger.LogInformation($"开始删除出货检验，ID：{id}");
                
                if (id <= 0)
                {
                    _logger.LogWarning($"删除出货检验时ID无效：{id}");
                    return Json(new { code = 1, msg = "出货检验ID无效" });
                }

                await _outgoingInspectionService.DeleteOutgoingInspection(id);
                
                _logger.LogInformation($"删除出货检验成功，ID：{id}");
                
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除出货检验失败，ID：{id}");
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }
    }
} 